|
|
|
|
|
|
|
You can also replace words in a document by assigning a value to the Text property, although you should keep in mind that replacing a single word with multiple words changes the number of words. |
|
|
|
|
|
|
|
|
|
The Word.Document object also contains Sentences and Paragraphs collections.  |
|
|
|
|
|
|
|
|
|
|
An easy way to insert text at a specific location is to use bookmarks. In Microsoft Word, you can place the cursor at a certain location and choose Bookmark from the Insert menu to create a named bookmark. From code, you can use the Bookmarks collection to identify a bookmark: |
|
|
|
|
|
|
|
|
Set objDoc = objWord.Documents.Add("D:\DATA\MyTemplate.DOT")
objDoc.Bookmarks("Name").Range.Text = "John Smith"
objDoc.Bookmarks("Address").Range.Text = "123 Fourth Street"
objdoc.SaveAs "D:\DATA\JSMITH.DOC" |
|
|
|
|
|
|
|
|
In this example, you create a new document from a custom template, add some data at the bookmark locations, and save the document and data to a new filename. Note that this code assumes that the document template MyTemplate contains predefined bookmarks. |
|
|
|
|
|
|
|
|
If you want to create a report using Word, you need to call methods and set properties to control the formatting of the report. One way to make your report look neat is to add tables to the document's Tables collection, as in the following code sample: |
|
|
|
|
|
|
|
|
Dim objTable As Word.Table
Set objTable = objDoc.Tables.Add(objDoc.Range(), 10, 2)
objTable.Cell(1, 1).Range.Text = "Hello"
objTable.Cell(1, 2).Range.Text = "Dolly
objTable.Columns(2).AutoFit |
|
|
|
|
|
|
|
|
The preceding code inserts a 10-row, 2-column table in the document and adds some text. Finally, the Autofit method is called on the second column to size it to the text in the column. |
|
|
|
|
|
|
|
|
Another interesting feature is the ability to add your own variables to open documents. This feature is useful, for example, if you have several documents open and need a way to identify them. To add a variable, make up a name and use the Add method of the Variables collection: |
|
|
|
|
|
|
|
|
objDoc.Variables.Add "EMPLOYEEID", "8675309" |
|
|
|
|
|
|
|
|
You can then use your variable to identify a document: |
|
|
|
|
|
|
|
|
For Each objDocTemp In objWord.Documents
If objDocTemp.Variables("EMPLOYEEID") = "8675309" Then
Set objDoc = objDocTemp
End If
Next objDocTemp |
|
|
|
|
|
|
|
|
For the preceding code to work, you must set objDoc to Nothing if it was used previously. |
|
|
|
|
|